<?php

/**
* Model 
* 
*/
class Generator_Model 
{
    
    /**
    * Key for session rows number value 
    * 
    */
    const ROWS_NUMBER = 'rows_number';
    
    const LOGGED = 'logged';
    
    /**
    * Min rows number 
    * 
    */
    const MIN_ROWS_NUMBER = 2;
    
    /**
    * Return values by given key
    * 
    * @param string $key
    * @return array
    */
    public function getValues($key) 
    {
        return get_array_element($_SESSION[Generator::SESSION_NAMESPACE], $key, array());
    }
    
    /**
    * Return number of rows
    * 
    * @param string $key
    * @return integer
    */
    public function countRows($key) 
    {
        return get_array_element($this->getValues($key), self::ROWS_NUMBER, self::MIN_ROWS_NUMBER);
    }
    
    /**
    * Set values with given key
    * 
    * @param array $values
    * @param integer $rows_number
    * @param string $key
    */
    public function setValues(array $values, $rows_number, $key) 
    {
        $_SESSION[Generator::SESSION_NAMESPACE][$key] = 
            $values + array(self::ROWS_NUMBER => $rows_number);
    }
    
    public function log($key) 
    {
        $data = $this->getValues($key);
        
        if (!array_key_exists(self::LOGGED, $data)) {
            database::update('counter', 
                array('`value`' => database::expression('`value` + 1')));
            
            $data += array(self::LOGGED => true);
            $this->setValues($data, $data[self::ROWS_NUMBER], $key);
        }
    }
    
}